package org.devgframwork.flowsystem.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.devgframwork.flowsystem.config.interceptors.AdminApiInterceptor;
import org.devgframwork.platform.support.filters.RequestWebFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.Collections;

/**
 * @author duheng
 * @Date 2021/11/13 17:09
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Autowired
    private SysConfig sysConfig;

    @Autowired
    private AdminApiInterceptor adminApiInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] noFilterUrls = sysConfig.getNoFilterUrls();
        registry.addInterceptor(adminApiInterceptor).addPathPatterns(SysConfig.filterUrls).excludePathPatterns(noFilterUrls);
    }

    @Bean
    public PaginationInnerInterceptor paginationInnerInterceptor() {
        PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setMaxLimit(-1L);
        paginationInterceptor.setDbType(DbType.MYSQL);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setOptimizeJoin(true);
        return paginationInterceptor;
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.setInterceptors(Collections.singletonList(paginationInnerInterceptor()));
        return mybatisPlusInterceptor;
    }

    @Bean
    public FilterRegistrationBean<RequestWebFilter> myFilterFilterRegistrationBean() {
        FilterRegistrationBean<RequestWebFilter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new RequestWebFilter());
        bean.setOrder(-1);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}
